package com.wzf.greattruth.zookeeper.lock;

import java.util.SortedSet;

import org.apache.commons.lang3.StringUtils;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZooKeeper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;

import com.wzf.greattruth.zookeeper.ZookeeperManager;
import com.wzf.greattruth.zookeeper.helper.ZookeeperHelper;
import com.wzf.greattruth.zookeeper.lock.watcher.DistributedWaitLockWatcher;
import com.wzf.greattruth.zookeeper.node.Node;

public class DistributedWaitLock {
    private static final Logger LOGGER = LoggerFactory.getLogger(DistributedWaitLock.class);

    private static final String LOCK_NODE_PREFIX = "lock-";
    private ZooKeeper zookeeper;
    /**
     * 父级目录
     */
    private String dir;
    /**
     * 当前创建的节点的node id
     */
    private String currentNodeId;
    /**
     * 是否是上锁成功
     */
    private boolean locked;

    /**
     * 如果希望监控上一个节点delete事件，可以添加此Watcher
     */
    private DistributedWaitLockWatcher<?> waitWatcher;

    private ZookeeperManager zookeeperManager = ZookeeperManager.getInstance();

    public DistributedWaitLock(ZooKeeper zookeeper, String dir, DistributedWaitLockWatcher<?> waitWatcher) {
        super();
        this.zookeeper = zookeeper;
        this.dir = dir;
        this.waitWatcher = waitWatcher;
        if (zookeeper == null || dir == null || waitWatcher == null) {
            new Exception("param error!");
        }
        waitWatcher.setZooKeeperDistributeLock(this);
    }

    public boolean lock() {
        if (StringUtils.isEmpty(dir)) {
            // 参数不对，返回错误
            return false;
        }

        // 创建父级目录失败，直接返回
        boolean createResult = zookeeperManager.createDirIfNotExist(zookeeper, dir);
        if (!createResult) {
            return false;
        }

        if (StringUtils.isBlank(currentNodeId)) {
            // 在parentDir目录下创建临时节点
            String path = ZookeeperHelper.getNodePath(dir, LOCK_NODE_PREFIX);
            String nodePath = zookeeperManager.createNode(zookeeper, path, null, CreateMode.EPHEMERAL_SEQUENTIAL);
            if (StringUtils.isBlank(nodePath)) {
                return false;
            }
            currentNodeId = ZookeeperHelper.getNodeId(nodePath);
//            System.err.println("currentNodeId="+currentNodeId);
        }

        // 判断是否获取到锁
        SortedSet<Node> nodes = zookeeperManager.getChildren(zookeeper, dir, LOCK_NODE_PREFIX);
        if (CollectionUtils.isEmpty(nodes)) {
            return false;
        }
        Node node = nodes.first();
        if (currentNodeId.equals(node.getId())) {
            // 当前node是最小的那个node，那么当前线程上锁成功
            locked = true;
            return true;
        }

        watchPreviousNode(nodes);
        return false;
    }

    public boolean unlock() {
        return unlock(false);
    }

    public boolean unlock(boolean force) {
        if (StringUtils.isEmpty(currentNodeId)) {
            // 未上过锁，所以直接返回true
            return true;
        }

        if (!locked && !force) {
            return false;
        }

        // 删除节点
        String path = ZookeeperHelper.getNodePath(dir, currentNodeId);
        boolean unlock = zookeeperManager.deleteNode(zookeeper, path);
        // 临时节点删除以后，清理数据
        if (unlock) {
            currentNodeId = null;
            locked = false;
        }
        return unlock;
    }

    private boolean watchPreviousNode(SortedSet<Node> nodes) {
        // 如果watcher为空，直接返回
        if (waitWatcher == null) {
            return false;
        }

        Node currentNode = new Node(dir, currentNodeId, LOCK_NODE_PREFIX);
        SortedSet<Node> preNodes = nodes.headSet(currentNode);
        if (preNodes.isEmpty()) {
            // 这种情况应该不会发生，因为除非当前node id是最小的，才会进入这里，此种情况下载之前的判断是就会返回true
            return true;
        }

        Node preNode = preNodes.last();
        String preNodeId = preNode.getId();
        String preNodePath = ZookeeperHelper.getNodePath(dir, preNodeId);
        boolean exist = zookeeperManager.exist(zookeeper, preNodePath, waitWatcher);
//        System.err.println(
//                "watch node result=" + exist + " currentNodeId=" + currentNodeId + "  nodepath=" + preNodePath);
        if (!exist) {
            return false;
        }
        return true;
    }

    public boolean isLocked() {
        return locked;
    }

}
